package com.seven.ezpermissions.helper

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Lifecycle.State.DESTROYED
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.seven.ezpermissions.OnDestroyEvent

/**
 * 说明
 * @author seven.xie
 * @date 2020/7/10 14:45
 * email: se7en.xie@qq.com
 */
class AppCompatActivityPermissionsHelper(host: AppCompatActivity) :

    BasePermissionsHelper<AppCompatActivity>(host) {

    override fun directRequest(requestCode: Int, permissions: Array<out String>) {
        host?.let { ActivityCompat.requestPermissions(it, permissions, requestCode) }
    }

    override fun shouldShowRationale(permission: String): Boolean {
        host?.let {
            return ActivityCompat.shouldShowRequestPermissionRationale(it, permission)
        }
        return false
    }

    override fun addLifecycleObserver(observer: LifecycleObserver) {
        host?.lifecycle?.addObserver(observer)
    }

    override fun onStateChanged(
        source: LifecycleOwner,
        event: Lifecycle.Event,
        observer: LifecycleObserver,
        callback: OnDestroyEvent
    ) {
        if (host?.lifecycle?.currentState == DESTROYED) {
            host?.lifecycle?.removeObserver(observer)
            onClear()
            callback()
        }
    }

    override val context: Context?
        get() = host
}